<template>
	<view class="orders-generate-area">
		<!-- 收货地址区域 -->
		<view class="chosen-address-area" @click="getAddressList">
			<view class="address-info">
				<block v-if="addressInfo">
					<view class="address">{{ addressInfo.address }}</view>
					<view class="person">{{ addressInfo.person + ' ' + addressInfo.tel }}</view>
				</block>
				<text v-else>请选择收获地址</text>
			</view>
			<van-icon name="arrow" />
		</view>
		<!-- 商品区域 -->
		<view class="goods-area">
			<block v-for="(item, index) in readyToSubmitGoods" :key="item.goodsid" >
				<shop-good :goodsimg="item.goodsimg" :goodsname="item.goodsname" :goodsprice="item.price">
					<template v-slot:choice>
						<van-cell :title="item.choicename" title-width="300rpx"/>
					</template>
					<template v-slot:stepper>
						<van-stepper :value="item.goodsnum" :input-width="20" :button-size="16" max="5" @change="numChange(index, $event)"/>
					</template>
				</shop-good>
				<!-- 商品附加服务 -->
				<view class="addtional-service">
					<van-cell title="配送服务" is-link center>
						<view>
							<view>快递 免邮</view>
							<view>现货,付款后48小时内发货</view>
						</view>
					</van-cell>
					<van-cell title="运费险" center >
						<view>
							<van-switch :checked="switchCheck[index]" @change="switchChange(index, $event)" />
						</view>
					</van-cell>
					<van-cell title="订单备注" :value="leftMessage.find(val => val.goodsid === item.goodsid).info" is-link @click="addOrderLeftMessage(item.goodsid)" />
				</view>
			</block>
		</view>
		<!-- 订单提交栏 -->
		<van-submit-bar
		  :price="totalPrice * 100"
		  button-text="提交订单"
		  @submit="onSubmit"
		/>
		<!-- 买家留言区popup弹出层 -->
		<van-popup
		  :show="showLeftMessage"
		  position="bottom"
			custom-style="height: 50%;padding: 40rpx"
			@close="closeLeftMessagePopup"
			z-index="101"
			closeable round>
			<text style="padding-bottom: 20rpx;">订单备注</text>
			<textarea name="leftmessagetextarea" cols="30" rows="10" maxlength="200" v-model="textAreaValue"></textarea>
		</van-popup>
		<!-- 展示选择用户收货地址的popup弹出框 -->
		<van-popup
		  :show="showAddressPopup"
		  position="bottom"
			custom-style="height: 50%;padding: 40rpx"
			z-index="101"
			@close="closeAddressPopup"
			closeable round>
			<block v-for="(item, index) in addressList" :key="index">
				<shop-address :username="item.person" :tel="item.tel" :address="item.address" @click.native="chosenCurrentAddress(item)"></shop-address>
			</block>
		</van-popup>
	</view>
</template>

<script>
	export default {
		onLoad(val) {
			this.getAddressInfo()
			if(val.type == 1) {
				this.getCheckedCartGoods()
				this.type = 1
			} else if(val.type == 0) {
				this.readyToSubmitGoods[0] = new Object()
				this.readyToSubmitGoods[0].goodsid = val.gid
				this.readyToSubmitGoods[0].choiceid = val.cid
				this.readyToSubmitGoods[0].goodsimg = val.img
				this.readyToSubmitGoods[0].goodsname = val.gname
				this.readyToSubmitGoods[0].choicename = val.cname
				this.readyToSubmitGoods[0].goodsnum = val.num
				this.readyToSubmitGoods[0].price = val.price
				this.readyToSubmitGoods[0].merchantsid = val.mid
				this.readyToSubmitGoods[0].merchantsname = val.mname
				this.getTotalPrice()
			}
		},
		data() {
			return {
				// 用户通过购物车来结算商品时值为1  通过商品详情页来结算商品值为0
				type: -1,
				// 存储用户选中信息的对象
				addressInfo: '',
				// 该用户所有的收货信息列表
				addressList: [],
				// 即将等待提交购买的商品
				readyToSubmitGoods: [],
				// 总价格
				totalPrice: 0,
				// 展示留言面板的popup弹出层
				showLeftMessage: false,
				// 用户当前正在编辑的商品留言
				activeGoodMessageId: '',
				// 买家订单留言信息列表
				leftMessage: [],
				// 留言框中的暂存值
				textAreaValue: '',
				// 是否选择运费险的开关
				switchCheck: [],
				// 是否展示用户收货地址的popup弹出层
				showAddressPopup: false
			}
		},
		methods: {
			// 从本地存储中获取用户选中的地址信息
			getAddressInfo() {
				if(!uni.getStorageSync('address')) return
				this.addressInfo = JSON.parse(uni.getStorageSync('address'))
			},
			// 用户收货地址的popup弹出框弹出后获取地址数据
			async getAddressList() {
				const { data: res } = await uni.$http.get('/address', { id: uni.getStorageSync('uid') })
				if(res.meta.status !== 200) {
					return uni.showToast({
						title: '地址信息失败',
						icon: 'error',
						duration: 1000
					})
				}
				this.addressList = res.recordset
				this.showAddressPopup = true
			},
			// 当选择用户收货信息地址的popup弹出框被关闭时触发
			closeAddressPopup() {
				this.showAddressPopup = false
			},
			// 当前收获信息被选中的时候触发
			chosenCurrentAddress(val) {
				uni.setStorageSync('address', JSON.stringify(val))
				this.getAddressInfo()
				this.showAddressPopup = false
			},
			// 获取总价格
			getTotalPrice() {
				this.totalPrice = 0
				this.readyToSubmitGoods.forEach(item => {
					this.totalPrice += item.goodsnum * item.price
				})
				console.log(this.totalPrice)
			},
			// 在购物车界面结算商品时触发获取此用户购物车中选中的所有商品 
			async getCheckedCartGoods() {
				const { data: res } = await uni.$http.get('/cart', { id: uni.getStorageSync('uid') })
				if(res.meta.status !== 200) {
					return uni.showToast({
						title: '选项值信息失败',
						icon: 'error',
						duration: 1000
					})
				}
				this.readyToSubmitGoods = res.recordset.filter(item => item.checked)
				for(let i = 0; i < this.readyToSubmitGoods.length; i++) {
					this.switchCheck.push(false)
				}
				this.getTotalPrice()
			},
			// 结算商品数量发生改变时触发
			numChange(index, e) {
				this.readyToSubmitGoods[index].goodsnum = e.detail
				this.getTotalPrice()
			},
			// 对当前商品进行留言
			addOrderLeftMessage(id) {
				this.activeGoodMessageId = id
				this.showLeftMessage = true
			},
			// 留言popup弹出层关闭时触发
			closeLeftMessagePopup() {
				this.showLeftMessage = false
				const index = this.leftMessage.findIndex(item => item.goodsid == this.activeGoodMessageId)
				if(index >= 0) this.leftMessage.splice(index, 1)
				if(this.textAreaValue.trim() === '') return
				this.leftMessage.push({
					goodsid: this.activeGoodMessageId,
					info: this.textAreaValue
				})
				this.textAreaValue = ''
			},
			// 当前商品是否选择运费险的开关状态变动之后触发
			switchChange(i, e) {
				this.$set(this.switchCheck, i, !this.switchCheck[i])
			},
			// 用户从购物车途径结算商品成功后要删除用户购物车中对应的商品数据信息
			async delOrdersGoods() {
				const ids = this.readyToSubmitGoods.map(item => item.goodsid).join(',')
				const { data: res } = await uni.$http.delete('/cart/del', { uid: uni.getStorageSync('uid'), id: ids })
				if(res.meta.status !== 200) {
					return console.log(res.meta)
				}
			},
			// 当前订单被提交时触发
			onSubmit() {
				if(!this.addressInfo) return uni.showToast({
					title: '请选择收货地址',
					icon: 'error',
					duration: 1000
				})
				console.log('hah')
				let that = this
				wx.showModal({
				  title: '提示',
				  content: `请支付${ that.totalPrice.toFixed(2) }元`,
				  success (res) {
				    if (res.confirm) {
				      for(let obj of that.readyToSubmitGoods) {
				      	that.commitAddANewOrder(obj)
				      }
							if(that.type === 1) {
								that.delOrdersGoods()
							}
							uni.navigateBack()
							uni.showToast({
								title: '下单成功',
								icon: 'success',
								duration: 1500
							})
				    } else if (res.cancel) {
				      console.log('用户点击取消')
				    }
				  }
				})
			},
			async commitAddANewOrder(obj) {
				let msgObj = this.leftMessage.find(item => item.goodsid === obj.goodsid)
				let msg = ''
				if(msgObj) {
					msg = msgObj.info
				}
				const { data: res } = await uni.$http.post('/user/addorder', {
					uid: uni.getStorageSync('uid'),
					gid: obj.goodsid,
					cid: obj.choiceid,
					num: obj.goodsnum,
					price: obj.price,
					mid: obj.merchantsid,
					msg,
					recordid: this.addressInfo.recordid
				})
				console.log(res.meta)
				if(res.meta.status !== 200) {
					return uni.showToast({
						title: res.meta.message,
						icon: 'error',
						duration: 1000
					})
				}
			}
		}
	}
</script>

<style>
	page {
		background-color: #f2f2f2;
	}
	
	.van-cell__title {
		font-size: 12px;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	
	.chosen-address-area {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 160rpx;
		padding: 0 40rpx;
		background-color: #fff;
	}
	
	.address-info {
		width: 90%;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
	}
	
	.address {
		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
	}
	
	.person {
		font-size: 14px;
		color: gray;
		margin-top: 10rpx;
	}
	
	.goods-area {
		margin-top: 30rpx;
		padding-bottom: 100rpx;
	}
	
	.van-submit-bar {
		display: flex;
		width: 100%;
	}
	
	.van-submit-bar__bar {
		width: 100%;
	}
	
	textarea[name=leftmessagetextarea] {
		background-color: #f0f0f0;
		margin-top: 20rpx;
		padding: 30rpx;
	}
	
	.van-cell__value {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>
